/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.csource.manage.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONArray;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.CertTypeEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.DateUtil;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.csource.manage.dto.CaseSourceLegalInfoUpdateDto;
import com.icinfo.cloud.provider.punish.csource.manage.dto.CaseSourcePartyInfoAdjustDto;
import com.icinfo.cloud.provider.punish.csource.manage.dto.CaseSourceRegisterCheckContentSaveDto;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourcePartyInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceRegisterDetailInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceRegisterMainInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourcePartyInfo;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceRegisterDetailInfo;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceRegisterMainInfo;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourcePartyInfoService;
import com.icinfo.cloud.provider.punish.csource.manage.vo.CaseSourcePartyInfoOfCheckVo;
import com.icinfo.cloud.provider.punish.csource.manage.vo.CaseSourcePartyInfoVo;
import com.icinfo.cloud.provider.punish.csource.manage.vo.CaseSourcePartyMsgVo;
import com.icinfo.cloud.provider.punish.evideinv.dto.CaseSourceEventSaveDto;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.EnterTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 案源线索当事人信息表（含个人+法人） case_source_party_info 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年08月12日
 */
@Slf4j
@Service
public class CaseSourcePartyInfoServiceImpl extends MyBatisServiceSupport implements ICaseSourcePartyInfoService {

    @Resource
    private CaseSourcePartyInfoMapper caseSourcePartyInfoMapper;

    @Resource
    private CaseSourceRegisterDetailInfoMapper caseSourceRegisterDetailInfoMapper;

    @Resource
    private IRegisterCommonService registerCommonService;

    @Resource
    private CaseSourceRegisterMainInfoMapper caseSourceRegisterMainInfoMapper;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;

    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseSourcePartyInfoServiceImpl.class);


    /**
     * 描述： 根据id删除当事人
     *
     * @author: zhengqiang
     * @date: 2022/8/15
     * @param: id
     * @return {@link Result}
     **/
    @Override
    public Result delCaseSourcePartyInfo(String id) {
        int count = caseSourcePartyInfoMapper.deleteByPrimaryKey(id);
        if (count > 0) {
            return Result.success(Constant.STRING_SUCCESS_CH);
        }
        return Result.error(Constant.STRING_FAIL_CH);
    }

    /**
     * 描述： 调整当事人
     *
     * @author: zhengqiang
     * @date: 2022/8/15
     * @param: caseSourcePartyInfoAdjustDto
     * @return {@link Result}
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateCaseSourcePartyInfo(CaseSourcePartyInfoAdjustDto caseSourcePartyInfoAdjustDto) {
        int successCount = 0;

        CaseSourcePartyInfo partyInfo = new CaseSourcePartyInfo();
        BeanUtils.copyProperties(caseSourcePartyInfoAdjustDto, partyInfo);

        String operateType = caseSourcePartyInfoAdjustDto.getOperateType();
        if ("ADD".equals(operateType)) {
            //检验用户信息是否重复
            checkPartyInfo(caseSourcePartyInfoAdjustDto);
            partyInfo.setId(BaseUtil.createUid());
            successCount = caseSourcePartyInfoMapper.insertSelective(partyInfo);

        } else if ("UPDATE".equals(operateType)) {
            if (ObjectUtils.isEmpty(caseSourcePartyInfoAdjustDto.getId())) {
                throw new BusinessException("调整当事人时当事人id不允许为空");
            }
            CaseSourcePartyInfo caseSourcePartyInfo = caseSourcePartyInfoMapper.selectByPrimaryKey(caseSourcePartyInfoAdjustDto.getId());
            if (ObjectUtils.isEmpty(caseSourcePartyInfo)) {
                throw new BusinessException("当事人记录不存在");
            }

            if (!caseSourcePartyInfo.getPartyIdentityCode().equals(caseSourcePartyInfoAdjustDto.getPartyIdentityCode())) {
                //证件号改变了需校验当事人是否重复
                checkPartyInfo(caseSourcePartyInfoAdjustDto);
            }

            successCount = caseSourcePartyInfoMapper.updateByPrimaryKeySelective(partyInfo);
        } else {
            throw new BusinessException("操作类型有误,operateType:" + operateType);
        }


        if (successCount > 0) {
            //更新案源主表当事人名称
            String caseSourcePartyName = getCaseSourcePartyName(caseSourcePartyInfoAdjustDto.getCaseSourceId());
            CaseSourceRegisterMainInfo mainInfo = new CaseSourceRegisterMainInfo();
            mainInfo.setId(caseSourcePartyInfoAdjustDto.getCaseSourceId());
            mainInfo.setPartyName(caseSourcePartyName);
            caseSourceRegisterMainInfoMapper.updateByPrimaryKeySelective(mainInfo);
            //同步取证端
            try {
                CaseSourceRegisterMainInfo caseSourceRegisterMainInfo=caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseSourcePartyInfoAdjustDto.getCaseSourceId());
                CaseSourceEventSaveDto dto = new CaseSourceEventSaveDto();
                dto.setCaseSourceId(caseSourceRegisterMainInfo.getId());
                dto.setCaseSourceName(caseSourceRegisterMainInfo.getCaseSourceName());
                dto.setTerritoryCode(caseSourceRegisterMainInfo.getLineCode().substring(0, 4));
                evidenceInventoryService.saveCaseSourceEvent(dto);
            } catch (Exception e) {
                logger.error("新增案源事件失败", e);
            }
            return Result.success(Constant.STRING_SAVE_SUCCESS);
        }
        return Result.error(Constant.STRING_SAVE_FAIL);
    }

    /**
     * 校验当事人是否重复
     *
     * @param caseSourcePartyInfoAdjustDto
     */
    private void checkPartyInfo(CaseSourcePartyInfoAdjustDto caseSourcePartyInfoAdjustDto){
        Example queryExample = new Example(CaseSourcePartyInfo.class);
        queryExample.createCriteria().andEqualTo("caseSourceId", caseSourcePartyInfoAdjustDto.getCaseSourceId())
                .andEqualTo("partyIdentityCode", caseSourcePartyInfoAdjustDto.getPartyIdentityCode())
                .andEqualTo("partyType", caseSourcePartyInfoAdjustDto.getPartyType())
                .andEqualTo("status", Constant.STRING_1);
        List<CaseSourcePartyInfo> caseSourcePartyInfos = caseSourcePartyInfoMapper.selectByExample(queryExample);
        if (!ObjectUtils.isEmpty(caseSourcePartyInfos)) {
            throw new BusinessException("该当事人已存在,请勿重复添加");
        }
    }

    /**
     * 描述： 查询案源当事人列表
     *
     * @author: zhengqiang
     * @date: 2022/8/15
     * @param: caseSourceId
     * @return {@link List< CaseSourcePartyInfoVo>}
     **/
    @Override
    public List<CaseSourcePartyInfoVo> getCaseSourcePartyInfo(String caseSourceId) {
        List<CaseSourcePartyInfoVo> caseSourcePartyInfoVos = new ArrayList<>();

        Example queryExample = new Example(CaseSourcePartyInfo.class);
        queryExample.createCriteria().andEqualTo("caseSourceId", caseSourceId).andEqualTo("status",Constant.STRING_1);
        List<CaseSourcePartyInfo> caseSourcePartyInfos = caseSourcePartyInfoMapper.selectByExample(queryExample);
        caseSourcePartyInfos.forEach(party -> {
            CaseSourcePartyInfoVo vo = new CaseSourcePartyInfoVo();
            BeanUtils.copyProperties(party, vo);
            vo.setPartyIdentityTypeName(CertTypeEnum.getValueByCode(party.getPartyIdentityType()));
            if (PartyTypeEnum.LEGAL.getCode().equals(party.getPartyType())){
                vo.setPartyIdentityTypeName("统一社会信用代码");
            }
            vo.setPersonBirthFormat(DateUtil.formatDateStr(vo.getPersonBirth()));
            vo.setPartyTypeName(PartyTypeEnum.getValueByCode(party.getPartyType()));
            vo.setEntTypeName(EnterTypeEnum.getValueByCode(party.getEntType()));
            vo.setLegalCertTypeName(CertTypeEnum.getValueByCode(party.getLegalCertType()));
            caseSourcePartyInfoVos.add(vo);
        });
        return caseSourcePartyInfoVos;
    }

    /**
     * 描述： 获取当事人列表
     *
     * @param: caseSourceId
     * @return {@link List< CaseSourcePartyInfoVo>}
     **/
    @Override
    public List<CaseSourcePartyMsgVo> getCaseSourcePartyInfoList(String caseSourceId){
        List<CaseSourcePartyMsgVo> reList = CollUtil.newArrayList();
        Example queryExample = new Example(CaseSourcePartyInfo.class);
        queryExample.createCriteria().andEqualTo("caseSourceId", caseSourceId).andEqualTo("status",Constant.STRING_1);
        queryExample.orderBy("partyType").desc();
        List<CaseSourcePartyInfo> caseSourcePartyList = caseSourcePartyInfoMapper.selectByExample(queryExample);
        caseSourcePartyList.forEach(party -> {
            CaseSourcePartyMsgVo vo = new CaseSourcePartyMsgVo();
            vo.setPartyId(party.getId());
            vo.setPersonType(party.getPartyType());
            if (PartyTypeEnum.PERSON.getCode().equals(party.getPartyType())) {
                vo.setName(party.getPartyName());
                reList.add(vo);
            } else if (PartyTypeEnum.LEGAL.getCode().equals(party.getPartyType())) {
                vo.setName(party.getPartyName());
                reList.add(vo);
            }
        });
        return reList;
    }


    /**
     * 描述： 查询案源当事人列表(检查转案源)
     *
     * @author: zhengqiang
     * @date: 2022/8/15
     * @param: caseSourceId
     * @return {@link List< CaseSourcePartyInfoVo>}
     **/
    @Override
    public CaseSourcePartyInfoOfCheckVo getCaseSourcePartyInfoOfCheck(String caseSourceId) {
        CaseSourcePartyInfoOfCheckVo vo = new CaseSourcePartyInfoOfCheckVo();
        Example queryExample = new Example(CaseSourcePartyInfo.class);
        queryExample.createCriteria().andEqualTo("caseSourceId", caseSourceId);
        List<CaseSourcePartyInfo> caseSourcePartyInfos = caseSourcePartyInfoMapper.selectByExample(queryExample);
        if (!ObjectUtils.isEmpty(caseSourcePartyInfos)) {
            //检查转案源只存在单当事人
            CaseSourcePartyInfo caseSourcePartyInfo = caseSourcePartyInfos.get(0);
            vo.setPartyName(caseSourcePartyInfo.getPartyName());
            vo.setPartyIdentityCode(caseSourcePartyInfo.getPartyIdentityCode());
            vo.setAddressDetail(caseSourcePartyInfo.getAddressDetail());
        }

        //查询检查内容
        Example checkExample = new Example(CaseSourceRegisterDetailInfo.class);
        checkExample.createCriteria().andEqualTo("caseSourceId", caseSourceId);
        List<CaseSourceRegisterDetailInfo> caseSourceRegisterDetailInfos = caseSourceRegisterDetailInfoMapper.selectByExample(checkExample);
        if (!ObjectUtils.isEmpty(caseSourceRegisterDetailInfos)) {
            CaseSourceRegisterDetailInfo detailInfo = caseSourceRegisterDetailInfos.get(0);
            vo.setCheckTaskNumber(detailInfo.getCheckTaskNumber());
            String checkPositionContent = detailInfo.getCheckPositionContent();
            List<CaseSourceRegisterCheckContentSaveDto> checkList = JSONArray.parseArray(checkPositionContent, CaseSourceRegisterCheckContentSaveDto.class);
            String checkContent = checkList.stream().map(e -> e.getCheckPositionName()).collect(Collectors.joining(","));
            vo.setCheckPositionContent(checkContent);
        }
        return vo;
    }

    /**
     * 描述： 补充案源法定代表人证件信息
     *
     * @author: zhengqiang
     * @date: 2022/8/16
     * @param: updateDto
     * @return {@link Result< String>}
     **/
    @Override
    public Result<String> updateCaseSourceLegalInfo(CaseSourceLegalInfoUpdateDto updateDto) {
        //判断法定代表人记录是否存在
        CaseSourcePartyInfo caseSourcePartyInfo = caseSourcePartyInfoMapper.selectByPrimaryKey(updateDto.getId());
        if (caseSourcePartyInfo == null) {
            return Result.error("案源法定代表人记录不存在");
        }

        //验证姓名和证件号码是否匹配
        if(StringUtils.isNotEmpty(updateDto.getLegalCertNo()) && "SFZ".equals(updateDto.getLegalCertType())){
            boolean flag = registerCommonService.checkRealNameDifferent(updateDto.getLegalCertNo(), updateDto.getLegalName());
            if(flag){
                return Result.error("证件号码和姓名不匹配");
            }
        }
        CaseSourcePartyInfo updateLegalInfo = new CaseSourcePartyInfo();
        BeanUtils.copyProperties(updateDto, updateLegalInfo);
        int i = caseSourcePartyInfoMapper.updateByPrimaryKeySelective(updateLegalInfo);
        if (i > 0) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }

    /**
     * 描述： 获取案源当事人显示名称(多当事人合并)
     *
     * @author: zhengqiang
     * @date: 2022/8/19
     * @param: caseSourceId
     * @return {@link String}
     **/
    @Override
    public String getCaseSourcePartyName(String caseSourceId) {
        String partyName = "";
        Example queryExample = new Example(CaseSourcePartyInfo.class);
        queryExample.createCriteria().andEqualTo("caseSourceId", caseSourceId);
        queryExample.orderBy("partyType").desc();
        queryExample.orderBy("createTime").asc();
        List<CaseSourcePartyInfo> caseSourcePartyInfos = caseSourcePartyInfoMapper.selectByExample(queryExample);
        if (!ObjectUtils.isEmpty(caseSourcePartyInfos)) {
            int size = caseSourcePartyInfos.size();
            if (size == 1) {
                partyName = caseSourcePartyInfos.get(0).getPartyName();
            } else {
                partyName = caseSourcePartyInfos.get(0).getPartyName() + "等" + size + "个当事人";
            }
        }
        return partyName;
    }
}
